package com.koro.spring;


import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

public class KoroApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String,BeanDefintion> beanDefintionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,Object> singletonObjectMap = new ConcurrentHashMap<>();
    private ArrayList<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public KoroApplicationContext(Class configClass) {
        this.configClass = configClass;

        // 扫描
        if (configClass.isAnnotationPresent(ComponeScan.class)) {
            ComponeScan componeScanAnnotation = (ComponeScan) configClass.getAnnotation(ComponeScan.class);
            String path = componeScanAnnotation.value();
            path = path.replace(".", "/");

            ClassLoader classLoader = KoroApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());

            if(file.isDirectory()){
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    if(fileName.endsWith(".class")) {
                        String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                        className = className.replace("/",".");
                        try {
                            Class<?> clazz = classLoader.loadClass(className);
                            if(clazz.isAnnotationPresent(Component.class)) {

                                if(BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(instance);
                                }

                                Component clazzAnnotation = clazz.getAnnotation(Component.class);
                                String beanName = clazzAnnotation.value();
                                if("".equals(beanName)) {
                                    // decapitalize方法会将传入的字符串首字母小写
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                // 处理单例、多例bean
                                BeanDefintion beanDefintion = new BeanDefintion();
                                beanDefintion.setType(clazz);
                                if(clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefintion.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefintion.setScope("singleton");
                                }
                                beanDefintionMap.put(beanName,beanDefintion);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        // 单例bean存储到单例池
        for (String beanName : beanDefintionMap.keySet()) {
            BeanDefintion beanDefintion = beanDefintionMap.get(beanName);
            if(beanDefintion.getScope().equals("singleton")) {
                Object bean = createBean(beanName,beanDefintion);
                singletonObjectMap.put(beanName,bean);
            }
        }

    }

    /**
     * 创建bean
     * @param beanName
     * @param beanDefintion
     * @return
     */
    private Object createBean(String beanName, BeanDefintion beanDefintion) {
        Class clazz = beanDefintion.getType();

        try {
            Object instance = clazz.getConstructor().newInstance();

            // 简易版依赖注入
            for (Field f : clazz.getDeclaredFields()) {
                if(f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    f.set(instance,getBean(f.getName()));
                }
            }

            // Aware回调
            if(instance instanceof BeanNameAware) {
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            // 初始化前
            for(BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessorBeforInitialization(beanName,instance);
            }

            //初始化
            if(instance instanceof InitializingBean) {
                ((InitializingBean)instance).afterPropertiesSet();
            }

            // 初始化后
            for(BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessorAfterInitialization(beanName,instance);
            }

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getBean(String beanName){
        BeanDefintion beanDefintion = beanDefintionMap.get(beanName);
        if(beanDefintion == null) {
            throw new NullPointerException();
        }
        String scope = beanDefintion.getScope();
        if(scope.equals("singleton")) {
            if(null == singletonObjectMap.get(beanName)) {
                Object bean = createBean(beanName, beanDefintion);
                singletonObjectMap.put(beanName,bean);
            }
            return singletonObjectMap.get(beanName);
        } else {
            return createBean(beanName,beanDefintion);
        }
    }
}
